package com.example.shipload_e;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import com.example.shipload_e.activitys.discharge_feedback.DischargeFinishFormActivity;
import com.example.shipload_e.album_tool.PublishedActivity;
import com.example.shipload_e.database_dao.DBUtil;
import com.example.shipload_e.huawei_push.PustDemoActivity;
import com.example.shipload_e.util.HttpActConstant;
import com.example.shipload_e.util.HttpConstant;
import com.example.shipload_e.util.HttpUtil;
import com.example.shipload_e.util.ParamsKeyNames;
import com.example.shipload_e.util.PersistentCookieStore;
import com.example.shipload_e.util.SharePreferenceUtil;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View.OnClickListener;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	private MainActivity	    THISAC	= MainActivity.this;
	private EditText	        accountInfo, passwordInfo;
	private TextView	        forgetPassword;
	private Button	            loginBn;
	ProgressDialog	            progressDialog;
	private SharePreferenceUtil	spu;

	// private MyHandler handlers;
	// private boolean flag = false;

	static class MyHandler extends Handler {
		WeakReference<MainActivity>	mActivity;

		MyHandler(MainActivity activity) {
			mActivity = new WeakReference<MainActivity>(activity);
		}

		@Override
		public void handleMessage(Message msg) {
			MainActivity theActivity = mActivity.get();
			theActivity.progressDialog.dismiss();
			Bundle data = msg.getData();
			switch (msg.what) {
				case HttpActConstant.LOGIN:
					if(HttpConstant.SUBMIT_SUCCESS.equals(data
					        .getString(HttpConstant.SUBMIT_SUCCESS))) {
						theActivity.spu.setAccount(data.getString(HttpConstant.ACCOUNT));
						theActivity.spu.setPassword(data.getString(HttpConstant.PASSWORD));
						Intent in = new Intent(theActivity, ShipMentWelcomeActivity.class);
						theActivity.startActivity(in);
						Toast.makeText(theActivity, data.getString("msg", "登录成功！"), Toast.LENGTH_SHORT)
						        .show();
					} else if(HttpConstant.SUBMIT_FAIL.equals(data
					        .getString(HttpConstant.SUBMIT_FAIL))) {
						Toast.makeText(theActivity, data.getString("msg", "登录失败，请重试！"), Toast.LENGTH_SHORT)
						        .show();
					}
					break;
				default:
					break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		progressDialog = new ProgressDialog(THISAC);
		spu = new SharePreferenceUtil(THISAC);
		// handlers = new MyHandler(THISAC);
		initView();
		// Intent in = new Intent(THISAC, PublishedActivity.class);
		// THISAC.startActivity(in);
	}

	private void initView() {
		PersistentCookieStore pcs = new PersistentCookieStore(getApplicationContext());
		System.out.println(pcs.getCookies());

		forgetPassword = (TextView) findViewById(R.id.forget_password);
		forgetPassword.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);

		accountInfo = (EditText) findViewById(R.id.account_info);
		passwordInfo = (EditText) findViewById(R.id.password_info);
		loginBn = (Button) findViewById(R.id.bnLogin);
		loginBn.setOnClickListener(ocl);

		accountInfo.setText(spu.getAccount());
		passwordInfo.setText(spu.getPassword());
		// accountInfo.setText("11122233344");
		// passwordInfo.setText("123");
	}

	private final OnClickListener	ocl	= new OnClickListener() {

		                                    @Override
		                                    public void onClick(View mView) {
			                                    switch (mView.getId()) {
													case R.id.bnLogin:

														if(accountInfo.getText().length() <= 0
														        || passwordInfo.getText().length() <= 0) {
															Toast.makeText(MainActivity.this, "不能为空！", Toast.LENGTH_SHORT)
															        .show();
															break;
														} else {
															{
																progressDialog
																        .setMessage("正在登录，请稍后。。。");
																progressDialog.show();
																final String userName = accountInfo
																        .getText().toString();
																final String password = passwordInfo
																        .getText().toString();
																Runnable runnable = new Runnable() {

																	@Override
																	public void run() {
																		String url = HttpActConstant.LOGIN_URL;
																		// HttpPost httpPost = new
																		// HttpPost(url);
																		List<NameValuePair> params = new ArrayList<NameValuePair>();
																		// List<NameValuePair> nvps
																		// =
																		// new
																		// ArrayList<NameValuePair>();

																		params.add(new BasicNameValuePair("user", userName));
																		params.add(new BasicNameValuePair("password", password));
																		params.add(new BasicNameValuePair(ParamsKeyNames.SUBMIT_TYPE, ParamsKeyNames.ANDROID));
																		try {
																			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "utf-8");
																			String result = HttpUtil
																			        .doPost(url, entity, THISAC);
																			progressDialog
																			        .dismiss();
																			if(HttpConstant.TIME_OUT_EXCEPTION
																			        .equals(result)) {
																				try {
																					Message msg = new Message();
																					msg.what = 1;
																					mHandler.sendMessage(msg);
																				} catch (Exception e) {
																					e.printStackTrace();
																				}
																			}
																			System.out
																			        .println(result);
																			JSONObject jrs = new JSONObject(result);
																			if("true"
																			        .equals(jrs
																			                .getString("rs"))) {
																				// 记忆最后登录成功的账号密码
																				spu.setAccount(userName);
																				spu.setPassword(password);
																				startActivity(new Intent(THISAC, ShipMentWelcomeActivity.class));
																				if(jrs.has("types")) {
																					DBUtil.saveTypes(THISAC, jrs
																					        .getJSONArray("types"));
																				}
																				if(jrs.has("units")) {
																					DBUtil.saveUnits(THISAC, jrs
																					        .getJSONArray("units"));
																				}

																			} else {}
																		} catch (Exception e) {
																			Message msg = new Message();
																			msg.what = 2;
																			mHandler.sendMessage(msg);
																			e.printStackTrace();
																		}

																	}

																};
																Thread thread = new Thread(runnable);
																thread.start();
																break;
															}
														}
													default:
														break;
												}
											}
	                                    };

	public boolean onKeyDown(int keyCode,KeyEvent event) {

		if(keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			// 这里重写返回键
			onDestroy();
			System.exit(0);
			return true;
		}
		return false;

	}

	Handler	mHandler	= new Handler() {
		                 public void handleMessage(Message msg) {
			                 switch (msg.what) {
								 case 1:
									 Toast.makeText(MainActivity.this, "登录超时，请重试！", Toast.LENGTH_SHORT)
									         .show();
									 break;
								 case 2:
									 Toast.makeText(MainActivity.this, "登录异常，请重试！", Toast.LENGTH_SHORT)
									         .show();
									 break;
							 }
							 super.handleMessage(msg);
						 }
	                 };

}
